package com.zebraphp.devtool.httpUtils.NetOkHttp.requestBuilder;

import com.zebraphp.devtool.httpUtils.NetOkHttp.IOkHttp;
import com.zebraphp.devtool.httpUtils.NetOkHttp.callback.ICallback;
import com.zebraphp.devtool.httpUtils.NetOkHttp.responseHandler.BaseHandler;
import com.zebraphp.devtool.util.ILog;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * POST 请求体 构建
 */
public class PostBuilder extends BaseWithParamBuilder<PostBuilder> {

    private String mJsonParamsStr = "";//扩展JSON格式请求参数

    /* json格式参数 POST提交给服务器 */
    public PostBuilder jsonParams(String json) {
        this.mJsonParamsStr = json;
        return this;
    }

    public PostBuilder(IOkHttp IOkHttp) {
        super(IOkHttp);
    }

    @Override
    public void addTaskQueue(BaseHandler responseHandler) {

        try {
            if (mUrl == null || mUrl.length() == 0) {
                throw new IllegalArgumentException("URL 地址 不能为空!!!");
            }

            //实例化 OkHttp库的构建器builder
            Request.Builder ok3Builder = new Request.Builder().url(mUrl);
            this.appendFinalHeadersToRequest(ok3Builder, mHeaders);

            if (mTag != null) {
                ok3Builder.tag(mTag);
            }

            if (mJsonParamsStr.length() > 0) {//说明通过Json形式的参数 来Post
                //上传json格式参数
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), mJsonParamsStr);
                ok3Builder.post(body);

            } else {
                //普通kv参数
                FormBody.Builder ok3EncodingBuilder = new FormBody.Builder();
                //添加请求参数
                this.putParamsToPostForm(ok3EncodingBuilder, mParams);
                ok3Builder.post(ok3EncodingBuilder.build());
            }

            Request ok3Request = ok3Builder.build();

            mIOkHttp.getOkHttpClient()
                    .newCall(ok3Request)
                    .enqueue(new ICallback(responseHandler));

        } catch (Exception e) {
            ILog.printLib("POST 请求队列 入队报错:" + e.getMessage());
            responseHandler.onError(0, e.getMessage());
        }
    }

    //添加请求参数到Request构建器中
    private void putParamsToPostForm(FormBody.Builder builder, Map<String, String> params) {

        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }
}
